package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.oa.core.entity.com.Leave;
import com.fz.us.oa.core.service.com.LeaveService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by dzw on 2017/12/11.
 */
@Controller
@RequestMapping(value = "/com/leave")
public class LeaveController extends BaseController {
    private static final long serialVersionUID = 5762440156226509883L;

    @Autowired
    private LeaveService leaveService;

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);
        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if ("1".equals(viewtype)) {
                //申请中
                searchResult = leaveService.paging(order,
                        "com.fz.us.oa.core.entity.com.Leave", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},params);
            }else if("2".equals(viewtype)){
                //已通过
                params.put("isFinished", 0);
                searchResult =  leaveService.paging(order,
                        "com.fz.us.oa.core.entity.com.Leave", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if("3".equals(viewtype)){
                //已完成
                params.put("isFinished", 1);
                searchResult =  leaveService.paging(order,
                        "com.fz.us.oa.core.entity.com.Leave", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished}, params);
            }
        }else{
            //所有单子
            searchResult = leaveService.paging(order,
                    "com.fz.us.oa.core.entity.com.Leave",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }
        List<Leave> leaveList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Leave leave : leaveList){
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(leave.getId());
            Set<User> users = taskEntity.getEditors();
            String editor = "";
            for(User editorName:users){
                editor += editorName.getName()+",";
            }
            if(StringUtils.isNotEmpty(editor)){
                editor = editor.substring(0, editor.length()-1);
            }
            rMap = new HashMap<String, Object>();
            rMap.put("id",leave.getId());
            rMap.put("leaveUser", leave.getLeaveUser()!=null?leave.getLeaveUser().getName():"");
            rMap.put("leaveType", leave.getLeaveType()!=null?leave.getLeaveType().getName():"");
            rMap.put("leaveDayNum", leave.getLeaveDayNum());
            rMap.put("leaveDate", DataUtil.DateToString(leave.getLeaveStartDate(),"yyyy-MM-dd")+ " ～ " +DataUtil.DateToString(leave.getLeaveEndDate(),"yyyy-MM-dd"));
            rMap.put("editor", editor);
            rMap.put("isComplete", leave.getIsComplete());
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> leaveTypeDict = getDictItems(user, "leaveType");
        if (StringUtils.isNotEmpty(keyId)){
            Leave leave=leaveService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("leave", leave);
        }
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        model.addAttribute("user", user);
        model.addAttribute("leaveTypeDict", leaveTypeDict);
        return "/com/leave_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {

        if(StringUtils.isNotEmpty(keyId)) {
            Leave leave=leaveService.get(keyId);
            String userEdit = userEdit(keyId);
            model.addAttribute("leave", leave);
            model.addAttribute("userEdit", userEdit);
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/leave_read";
    }

    /**
     * 赋值数据
     */
    public Leave setData(User user, String keyId, String leaveUserId, String leaveTypeId, double leaveDayNum, String leaveStartDate,
                         String leaveEndDate, String leaveReason){
        Leave leave=null;
        if(StringUtils.isEmpty(keyId)){
            leave=new Leave();
            leave.setCreater(user);
            leave.setCompany(user.getCompany());
        }else{
            leave=leaveService.get(keyId);
        }
        leave.setLeaveUser(userService.get(leaveUserId));
        leave.setLeaveType(dictItemService.get(leaveTypeId));
        leave.setLeaveDayNum(leaveDayNum);
        leave.setLeaveStartDate(DataUtil.StringToDate(leaveStartDate));
        leave.setLeaveEndDate(DataUtil.StringToDate(leaveEndDate));
        leave.setLeaveReason(leaveReason);

        return leave;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String keyId, String leaveUserId, String leaveTypeId, double leaveDayNum, String leaveStartDate,
                       String leaveEndDate, String leaveReason) {
        Map<String,Object> rMap=new HashMap<String,Object>();

        Leave leave=setData(user,keyId,leaveUserId,leaveTypeId,leaveDayNum,leaveStartDate,leaveEndDate,leaveReason);
        if(StringUtils.isNotEmpty(keyId)){
            leaveService.update(leave);
            rMap.put("message", "更新成功");
        } else {
            leaveService.save(leave, "com.fz.us.oa.core.entity.com.Leave");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    // 提交
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, String keyId, String leaveUserId, String leaveTypeId, double leaveDayNum, String leaveStartDate,
                         String leaveEndDate, String leaveReason, String comment, String next, String editorsId, String remindUserId){
        User editor = null;
        if(StringUtils.isNotEmpty(editorsId)){
            editor = userService.get(editorsId);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        Leave leave=setData(user,keyId,leaveUserId,leaveTypeId,leaveDayNum,leaveStartDate,leaveEndDate,leaveReason);
        if (StringUtils.isNotEmpty(keyId)) {
            leaveService.approve(leave, user, comment, next, editor);
        } else {
            keyId=leaveService.commit(leave, "com.fz.us.oa.core.entity.com.Leave", user, next, editor);
        }
        toRemind("leave", keyId, remindUserId, user.getName()+"提交的请假申请，请查看");
        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String comment, String next, String editorsId, String remindUserId){
        User editor = null;
        if(StringUtils.isNotEmpty(editorsId)){
            editor = userService.get(editorsId);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        Leave leave=leaveService.get(keyId);
        leaveService.approve(leave, user, comment, next, editor);
        toRemind("leave", keyId, remindUserId, user.getName() + "提交的请假申请，请查看");
        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //退回
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String backStepNo, String comment, String remindUserId) {
        if (StringUtils.isNotEmpty(keyId)) {
            Leave leave=leaveService.get(keyId);
            if(StringUtils.isNotEmpty(backStepNo)){
                String[] arr = backStepNo.split("\\|");
                int stepNo = Integer.parseInt(arr[0]);
                User editor = userService.get(arr[1]);
                leaveService.back(leave, comment, stepNo, editor);
                toRemind("leave", keyId, remindUserId, user.getName() + "退回的请假申请，请查看");
            }
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //否决
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId, String comment, String remindUserId) {
        if (StringUtils.isNotEmpty(keyId)) {
            Leave leave=leaveService.get(keyId);
            leaveService.deny(leave, comment);
            toRemind("leave", keyId, remindUserId, user.getName()+"否决的请假申请，请查看");
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //验证身份
    @RequestMapping(value = "checkUser", method = RequestMethod.GET)
    public Object checkUser(@CurrentUser User user, String keyId){
        if(StringUtils.isEmpty(keyId)) return ajaxJson(resultService.fail("找不到文档id"));
        Leave leave=leaveService.get(keyId);
        if(leave==null) return ajaxJson(resultService.fail("找不到文档"));

        if(user.equals(leave.getLeaveUser())){
            return ajaxJson(resultService.success("验证通过"));
        }else{
            return ajaxJson(resultService.fail("需要由此表的请假人员操作"));
        }
    }

    //请假完成页面
    @RequestMapping(value = "leaveFinishPage", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String leaveFinishPage(@CurrentUser User user, String keyId, Model model){
        model.addAttribute("leaveId",keyId);
        return "/com/leave_finish_input";
    }

    //完成操作
    @RequestMapping(value = "saveFinish", method = RequestMethod.POST)
    public Object saveFinish(String leaveId, String isComplete){
        if(StringUtils.isEmpty(leaveId)) return ajaxJson(resultService.fail("找不到文档id"));
        Leave leave=leaveService.get(leaveId);
        if(leave!=null){
            leave.setIsComplete(isComplete);
            leave.setIsFinished(1);
            leaveService.update(leave);
            return ajaxJson(resultService.success("已完成"));
        }else{
            return ajaxJson(resultService.fail("找不到文档"));
        }
    }

}
